package com.sen.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sen.mapper.BmsPostMapper;
import com.sen.mapper.BmsTagMapper;
import com.sen.mapper.UmsUserMapper;
import com.sen.model.dto.CreateTopicDTO;
import com.sen.model.vo.ProfileVO;
import com.sen.model.entity.BmsPost;
import com.sen.model.entity.BmsPostTag;
import com.sen.model.entity.BmsTag;
import com.sen.model.entity.UmsUser;
import com.sen.model.vo.PostVO;
import com.sen.service.BmsPostService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sen.service.BmsPostTagService;
import com.sen.service.BmsTagService;
import com.sen.service.UmsUserService;
import com.vdurmont.emoji.EmojiParser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 话题表 服务实现类
 * </p>
 *
 * @author ergou
 * @since 2021-04-12
 */
@Service
public class BmsPostServiceImpl extends ServiceImpl<BmsPostMapper, BmsPost> implements BmsPostService {
    @Resource
    private BmsTagMapper bmsTagMapper;

    @Autowired
    private BmsPostTagService bmsPostTagService;

    @Resource
    private UmsUserMapper umsUserMapper;

    @Resource
    private UmsUserService umsUserService;
    @Resource
    private BmsTagService bmsTagService;

    @Override
    public Page<PostVO> getList(Page<PostVO> page, String tab) {
        // 查询话题
        Page<PostVO> iPage  = this.baseMapper.selectListAndPage(page,tab);

        //查询话题的标签,保存帖子标签
        iPage .getRecords().forEach(topic->{
            List<BmsPostTag> topicTags = bmsPostTagService.selectByTopicId(topic.getId());
            if (!topicTags.isEmpty()){
                List<String> tagIds = topicTags.stream().map(BmsPostTag::getTagId).collect(Collectors.toList());
                List<BmsTag> tags = bmsTagMapper.selectBatchIds(tagIds);
                topic.setTags(tags);
            }
        });
        return iPage;
    }

    //设计到多个数据库表操作，用事务管理
    @Override
    @Transactional(rollbackFor = Exception.class)
    public BmsPost create(CreateTopicDTO dto, UmsUser user) {
        //查找标题是否重复
        BmsPost topic1 = this.baseMapper.selectOne(new LambdaQueryWrapper<BmsPost>().eq(BmsPost::getTitle, dto.getTitle()));
        Assert.isNull(topic1,"话题已存在，请修改");

        //封装，创建新的帖子对象
        BmsPost bmsPost = BmsPost.builder()
                .userId(user.getId())
                .title(dto.getTitle())
                .content(EmojiParser.parseToAliases(dto.getContent()))
                .createTime(new Date())
                .build();
        this.baseMapper.insert(bmsPost);

        //用户积分增加
        int newScore = user.getScore() + 1;

        umsUserMapper.updateById(user.setScore(newScore));

        // 标签
        if (!ObjectUtils.isEmpty(dto.getTags())) {
            // 保存标签
            List<BmsTag> tags = bmsTagService.insertTags(dto.getTags());
            // 处理标签与话题的关联
            bmsPostTagService.createTopicTag(bmsPost.getId(), tags);
        }
        return bmsPost;
    }

    @Override
    public Map<String, Object> viewTopic(String id) {
        Map<String, Object> map = new HashMap<>(16);
        //根据帖子Id找到帖子
        BmsPost topic = this.baseMapper.selectById(id);
        Assert.notNull(topic, "当前话题不存在,或已被作者删除");
        // 查询话题详情，浏览次数加1
        topic.setView(topic.getView() + 1);
        this.baseMapper.updateById(topic);
        // 帖子里面如果有表情 emoji转码
        topic.setContent(EmojiParser.parseToUnicode(topic.getContent()));
        map.put("topic", topic);
        // 根据帖子标签id 去管理表找到 标签
        QueryWrapper<BmsPostTag> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(BmsPostTag::getTopicId, topic.getId());
        Set<String> set = new HashSet<>();
        for (BmsPostTag articleTag : bmsPostTagService.list(wrapper)) {
            set.add(articleTag.getTagId());
        }
        List<BmsTag> tags = bmsTagService.listByIds(set);
        map.put("tags", tags);

        // 作者
        ProfileVO user = umsUserService.getUserProfile(topic.getUserId());
        map.put("user", user);

        return map;
    }

    @Override
    public Page<PostVO> searchByKey(String keyword, Page<PostVO> page) {
        // 查询话题
        Page<PostVO> iPage = this.baseMapper.searchByKey(page, keyword);
        // 查询话题的标签
        setTopicTags(iPage);
        return iPage;
    }

    private void setTopicTags(Page<PostVO> iPage) {
        iPage.getRecords().forEach(topic -> {
            List<BmsPostTag> topicTags = bmsPostTagService.selectByTopicId(topic.getId());
            if (!topicTags.isEmpty()) {
                List<String> tagIds = topicTags.stream().map(BmsPostTag::getTagId).collect(Collectors.toList());
                List<BmsTag> tags = bmsTagMapper.selectBatchIds(tagIds);
                topic.setTags(tags);
            }
        });
    }
}
